%%%-------------------------------------------------------------------
%%% @author Zheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 21. 3月 2024 12:05
%%%-------------------------------------------------------------------
-module(concurrent_example).
-export([start/0, worker/1, handle_reply/2]).

start() ->
  % 创建三个工作进程
  Pid1 = spawn(?MODULE, worker, ["Worker 1"]),
  Pid2 = spawn(?MODULE, worker, ["Worker 2"]),
  Pid3 = spawn(?MODULE, worker, ["Worker 3"]),

  % 向各个工作进程发送消息
  Pid1 ! {self(), "Hello, Worker 1!"},
  Pid2 ! {self(), "Hello, Worker 2!"},
  Pid3 ! {self(), "Hello, Worker 3!"},

  % 接收来自工作进程的回复消息
  receive
    {Pid1, Msg} -> handle_reply(self(), Msg);
    {Pid2, Msg} -> handle_reply(self(), Msg);
    {Pid3, Msg} -> handle_reply(self(), Msg)
  end,
  receive
    {Pid1, Msg} -> handle_reply(self(), Msg);
    {Pid2, Msg} -> handle_reply(self(), Msg);
    {Pid3, Msg} -> handle_reply(self(), Msg)
  end,
  receive
    {Pid1, Msg} -> handle_reply(self(), Msg);
    {Pid2, Msg} -> handle_reply(self(), Msg);
    {Pid3, Msg} -> handle_reply(self(), Msg)
  end.

worker(Name) ->
  receive
    {From, Msg} ->
      io:format("~p received: ~p~n", [Name, Msg]),
      From ! {self(), "Message received!"}
  end.

handle_reply(From, Msg) ->
  io:format("~p received: ~p~n", [From, Msg]).
